<template>
  <div class="forecast-detail-container">
    <header class="header">
      <div class="header-content">
        <router-link to="/" class="back-link">
          <i class="bi bi-arrow-left"></i> 返回
        </router-link>
        <h1>{{ city }} {{ province }} 天气预报详情</h1>
      </div>
    </header>

    <main class="main-content">
      <div class="page-container">
        <div v-if="loading" class="loading-container">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p>正在加载天气数据...</p>
        </div>

        <div v-else-if="error" class="error-container">
          <div class="alert alert-danger">
            {{ error }}
          </div>
          <button class="btn btn-primary" @click="fetchData">重试</button>
        </div>

        <div v-else class="charts-container">
          <!-- 温度曲线图 -->
          <div class="chart-card">
            <div class="card-header">
              <h3>未来七天温度趋势</h3>
            </div>
            <div class="card-body">
              <div ref="temperatureChartRef" class="chart-container"></div>
            </div>
          </div>

          <!-- 温度对比柱状图 -->
          <div class="chart-card">
            <div class="card-header">
              <h3>最高/最低温度对比</h3>
            </div>
            <div class="card-body">
              <div ref="tempBarChartRef" class="chart-container"></div>
            </div>
          </div>

          <!-- 降水/湿度图 -->
          <div class="chart-card">
            <div class="card-header">
              <h3>降水量与湿度变化</h3>
            </div>
            <div class="card-body">
              <div ref="precipChartRef" class="chart-container"></div>
            </div>
          </div>

          <!-- 数据表格 -->
          <div class="data-table-card">
            <div class="card-header">
              <h3>详细天气数据</h3>
            </div>
            <div class="card-body">
              <table class="table table-striped table-hover">
                <thead>
                  <tr>
                    <th>日期</th>
                    <th>天气</th>
                    <th>最高温度</th>
                    <th>最低温度</th>
                    <th>降水量</th>
                    <th>湿度</th>
                    <th>风向</th>
                    <th>风速</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in forecastData" :key="index">
                    <td>{{ formatDate(item.date) }}</td>
                    <td>
                      <i :class="`qi-${item.iconDay} qi-24`"></i>
                      {{ item.textDay }}
                    </td>
                    <td>{{ item.temperatureHigh }}°C</td>
                    <td>{{ item.temperatureLow }}°C</td>
                    <td>{{ item.precipitation }}mm</td>
                    <td>{{ item.humidity }}%</td>
                    <td>{{ item.windDirection }}</td>
                    <td>{{ item.windSpeed }}km/h</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </main>

    <footer class="footer">
      <div class="footer-content">
        <p>© 2023 天气预报应用 | 数据来源：和风天气</p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { weatherApi } from '../api'
import * as echarts from 'echarts/core'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent,
  LineChart,
  BarChart,
  CanvasRenderer
])

// 路由相关
const route = useRoute()
const router = useRouter()
const city = ref(route.params.city || '')
const province = ref(route.params.province || '')

// 数据状态
const loading = ref(true)
const error = ref(null)
const forecastData = ref([])

// 图表引用
const temperatureChartRef = ref(null)
const tempBarChartRef = ref(null)
const precipChartRef = ref(null)

// 图表实例
let temperatureChart = null
let tempBarChart = null
let precipChart = null

// 窗口调整处理
let resizeHandler = null

// 生命周期钩子
onMounted(async () => {
  // 验证参数
  if (!city.value || !province.value) {
    error.value = '城市信息不完整，无法获取天气数据'
    loading.value = false
    return
  }

  // 初始化数据
  await fetchData()

  // 使用定时器确保DOM完全渲染后再初始化图表
  setTimeout(() => {
    // 初始化图表
    if (forecastData.value.length > 0) {
      initCharts()
    }
    
    // 窗口大小变化时调整图表
    resizeHandler = () => {
      temperatureChart?.resize()
      tempBarChart?.resize()
      precipChart?.resize()
    }
    window.addEventListener('resize', resizeHandler)
  }, 100)
})

onUnmounted(() => {
  // 清理图表实例
  temperatureChart?.dispose()
  tempBarChart?.dispose()
  precipChart?.dispose()

  // 移除事件监听
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler)
  }
})

// 获取天气数据
async function fetchData() {
  loading.value = true
  error.value = null

  try {
    // 使用新的API方法获取天气预报详情
    const response = await weatherApi.getCityForecastDetail(city.value, province.value)
    if (response?.data?.weather?.forecasts) {
      forecastData.value = response.data.weather.forecasts
      
      // 显示数据来源
      console.log(`天气数据来源: ${response.data.source}`)
    } else {
      error.value = '获取天气数据失败：数据格式不正确'
    }
  } catch (err) {
    console.error('获取天气数据失败:', err)
    error.value = '获取天气数据失败：' + (err.message || '未知错误')
  } finally {
    loading.value = false
  }
}

// 初始化所有图表
function initCharts() {
  if (forecastData.value.length === 0) return

  initTemperatureChart()
  initTempBarChart()
  initPrecipChart()
}

// 初始化温度曲线图
function initTemperatureChart() {
  // 确保DOM元素存在
  if (!temperatureChartRef.value) {
    console.error('温度图表容器DOM元素不存在')
    return
  }

  // 清理已有实例
  if (temperatureChart) {
    temperatureChart.dispose()
  }

  const dates = forecastData.value.map(item => formatDate(item.date))
  const highTemps = forecastData.value.map(item => item.temperatureHigh)
  const lowTemps = forecastData.value.map(item => item.temperatureLow)

  try {
    temperatureChart = echarts.init(temperatureChartRef.value)
    temperatureChart.setOption({
      title: {
        text: '七天温度趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          let result = params[0].name + '<br/>'
          params.forEach(param => {
            const marker = `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>`
            result += marker + param.seriesName + ': ' + param.value + '°C<br/>'
          })
          return result
        }
      },
      legend: {
        data: ['最高温度', '最低温度'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates
      },
      yAxis: {
        type: 'value',
        name: '温度(°C)',
        axisLabel: {
          formatter: '{value} °C'
        }
      },
      series: [
        {
          name: '最高温度',
          type: 'line',
          data: highTemps,
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#FF9800'
          },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#FF9800'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(255, 152, 0, 0.5)' },
              { offset: 1, color: 'rgba(255, 152, 0, 0.1)' }
            ])
          }
        },
        {
          name: '最低温度',
          type: 'line',
          data: lowTemps,
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#03A9F4'
          },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#03A9F4'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(3, 169, 244, 0.5)' },
              { offset: 1, color: 'rgba(3, 169, 244, 0.1)' }
            ])
          }
        }
      ]
    })
  } catch (error) {
    console.error('初始化温度曲线图失败:', error)
  }
}

// 初始化温度对比柱状图
function initTempBarChart() {
  // 确保DOM元素存在
  if (!tempBarChartRef.value) {
    console.error('温度柱状图容器DOM元素不存在')
    return
  }

  // 清理已有实例
  if (tempBarChart) {
    tempBarChart.dispose()
  }

  const dates = forecastData.value.map(item => formatDate(item.date))
  const highTemps = forecastData.value.map(item => item.temperatureHigh)
  const lowTemps = forecastData.value.map(item => item.temperatureLow)

  try {
    tempBarChart = echarts.init(tempBarChartRef.value)
    tempBarChart.setOption({
      title: {
        text: '七天最高/最低温度对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['最高温度', '最低温度'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        data: dates
      },
      yAxis: {
        type: 'value',
        name: '温度(°C)',
        axisLabel: {
          formatter: '{value} °C'
        }
      },
      series: [
        {
          name: '最高温度',
          type: 'bar',
          data: highTemps,
          itemStyle: {
            color: '#FF9800'
          },
          barMaxWidth: 40,
          label: {
            show: true,
            position: 'top',
            formatter: '{c} °C'
          }
        },
        {
          name: '最低温度',
          type: 'bar',
          data: lowTemps,
          itemStyle: {
            color: '#03A9F4'
          },
          barMaxWidth: 40,
          label: {
            show: true,
            position: 'top',
            formatter: '{c} °C'
          }
        }
      ]
    })
  } catch (error) {
    console.error('初始化温度柱状图失败:', error)
  }
}

// 初始化降水/湿度图
function initPrecipChart() {
  // 确保DOM元素存在
  if (!precipChartRef.value) {
    console.error('降水湿度图容器DOM元素不存在')
    return
  }

  // 清理已有实例
  if (precipChart) {
    precipChart.dispose()
  }

  const dates = forecastData.value.map(item => formatDate(item.date))
  const precip = forecastData.value.map(item => item.precipitation)
  const humidity = forecastData.value.map(item => item.humidity)

  try {
    precipChart = echarts.init(precipChartRef.value)
    precipChart.setOption({
      title: {
        text: '降水量与湿度变化',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['降水量', '湿度'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        data: dates
      },
      yAxis: [
        {
          type: 'value',
          name: '降水量(mm)',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#4CAF50'
            }
          },
          axisLabel: {
            formatter: '{value} mm'
          }
        },
        {
          type: 'value',
          name: '湿度(%)',
          min: 0,
          max: 100,
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#2196F3'
            }
          },
          axisLabel: {
            formatter: '{value} %'
          }
        }
      ],
      series: [
        {
          name: '降水量',
          type: 'bar',
          data: precip,
          yAxisIndex: 0,
          itemStyle: {
            color: '#4CAF50'
          },
          barMaxWidth: 30
        },
        {
          name: '湿度',
          type: 'line',
          data: humidity,
          yAxisIndex: 1,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3,
            color: '#2196F3'
          },
          itemStyle: {
            color: '#2196F3'
          }
        }
      ]
    })
  } catch (error) {
    console.error('初始化降水湿度图失败:', error)
  }
}

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return '未知'
  
  try {
    const date = new Date(dateStr)
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekday = weekdays[date.getDay()]
    
    return `${date.getMonth() + 1}月${date.getDate()}日 ${weekday}`
  } catch (error) {
    return dateStr
  }
}
</script>

<style scoped>
.forecast-detail-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.header {
  background-color: #409eff;
  color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 15px 20px;
  display: flex;
  align-items: center;
}

.back-link {
  color: white;
  text-decoration: none;
  margin-right: 20px;
  font-size: 16px;
}

.header-content h1 {
  margin: 0;
  font-size: 20px;
}

.main-content {
  flex: 1;
  padding-top: 70px;
  padding-bottom: 20px;
  background-color: #f5f7fa;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  text-align: center;
}

.loading-container p {
  margin-top: 20px;
  color: #606266;
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-card,
.data-table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chart-card:nth-child(1),
.chart-card:nth-child(2),
.data-table-card {
  grid-column: span 2;
}

.card-header {
  border-bottom: 1px solid #ebeef5;
  padding: 12px 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.card-body {
  padding: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.footer {
  background-color: #303133;
  color: #909399;
  padding: 20px 0;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  text-align: center;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .chart-card:nth-child(1),
  .chart-card:nth-child(2),
  .data-table-card {
    grid-column: span 1;
  }
  
  .chart-container {
    height: 300px;
  }
}
</style> 